<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller_Template
{

    public $template = 'main_template_view';
    var $P_COUNT = 12;

    public function action_index()
    {
        // ORM::factory('...')->orberby( DB::expr('RAND()') )->find();
        $images = ORM::factory('image'); // ограничить количество
        $count_all = $images->count_all(); // число всех картинок
        $count_all = ($count_all / $this->P_COUNT);
        if ($count_all > (int) $count_all) $count_all = (int) $count_all + 1;
        if ($count_all === 1) $count_all = 0;
        $this->template->lib = view::factory('library_view', array( 
                    'page_count' => $count_all
        ));
        $this->template->content = '<span style="display:block; margin: 30px auto; width: 180px; font-size: 40px;">Библиотека</span>';
        $this->template->errore = Session::instance()->get('errore');
        session::instance()->set('errore', '');
    }

    public function action_upload()
    { // после аплоада перенапавл на создание превью. И там же загоняем в базу.
        if ($this->request->method() === Request::POST)
        {
            $validation = Validation::factory($_FILES)
                    ->rules('image', array(
                array('upload::not_empty'),
                array('upload::image'),
                array('upload::size', array(':value', '2M')),
                array('upload::type', array(':value', array('png', 'jpg')))
            ));

            if ($validation->check())
            {
                $filename = 'assets/img/preview';
                if (!file_exists($filename)) mkdir($filename);
                $name = str_replace(' ', '_', $_FILES['image']['name']);
                $name = mb_strtolower($name);
                $l = model::factory('letters');
                $name = str_replace($l->rus, $l->lat, $name);
                $add = ORM::factory('image')->where('name', '=', $name)->find();
                Upload::save($validation['image'], $name, DOCROOT . 'assets/img/');
                session::instance()->set('errore', 'All ok load!');

                //image resize
                $image = image::factory('assets/img/' . $name);
                $obj = getimagesize('assets/img/' . $name);
                $width = $obj[0];
                $height = $obj[1];
                if ($width > 600 && $height > 800)
                {
                    $w = 600;
                    $h = 800;
                }
                else
                {
                    $w = 300;
                    $h = 400;
                }
                if ($width > 150 && $height > 200)
                {
                    $image->crop($w, $h);
                    $image->resize(150, 200);
                }
                $image->save('assets/img/preview/' . $name);

                // save BD info проверять на повторение
                $add->set('path', '/assets/img/' . $name);
                $add->set('preview', '/assets/img/preview/' . $name);
                $add->set('size', $_FILES['image']['size']);
                $add->set('name', $name);
                $add->set('width', $width);
                $add->set('height', $height);
                $add->set('alt', $_POST['description']);
                $add->save();
            }
            else
            {
                session::instance()->set('errore', 'No upload not validation!!!');
            }
        }

        $this->request->redirect('http://lib.w/');
    }

    public function action_getBigPic()
    {
        $request = Array();
        $id = -1;
        isset($_POST['id']) ? $id = $_POST['id'] : $id = -1;
        if ($id > -1)
        {
            $image = ORM::factory('image')->where('id', '=', $id)->find();
            $request['width'] = $image->width;
            $request['height'] = $image->height;
            $request['file'] = '<img src="' . $image->path . '" />';
            $request['info'] = 'Описание: '.$image->alt . '<br/> Путь: ' . $image->path . '<br/> Размер: '. $image->width .
                                'x' . $image->height . ' ( ' . (int)($image->size/1024) . ' kb)';
        }
        else
        {
            $request['errore'] = 'Не удалось сделать запрос';
        }
        echo json_encode($request);
        die;
    }

    public function action_setCurrentPage()
    {
        isset($_POST['numb']) ? $numb = $_POST['numb'] : $numb = 1;
        $images = ORM::factory('image');
        $count_all = $images->count_all();
        $next_page = $images->limit($this->P_COUNT)->offset((int) ($numb * $this->P_COUNT))->find_all();
        $images = $images->limit($this->P_COUNT)->offset((int) ($numb * $this->P_COUNT - $this->P_COUNT))->find_all();
        $request = Array();
        $count_all = ($count_all / $this->P_COUNT);
        if ($count_all > (int) $count_all) $count_all = (int) $count_all + 1;
        $request['page_numb'] = $count_all;
        $request['images'] = '';
        $i = 0;
        foreach ($images as $image)
        {
            $i++;
            $request['images'] .= '<a id="' . $i . '" href="' . $image->path . '"><img class="picture" id="' . $image->id . '" 
                src="' . $image->preview . '" /></a>';
        }
        $request['next'] = '';
        foreach ($next_page as $image)
        {
            $request['next'] .= '<img src="' . $image->preview . '" />'; // загружать превью или полные картинки? 
        }

        echo json_encode($request);
        die;
    }

}

// End Welcome
